package absc.util;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

import absc.bd.ConexaoBanco;

public class CreateWorkspace extends WorkspaceModifyOperation {
	
	private IProject project;
	private IProjectDescription projectDescription;
	private ConexaoBanco bd;

	public CreateWorkspace(IProject newProject, IProjectDescription description, ConexaoBanco conexaoBanco) {
		this.project = newProject;
		this.projectDescription = description;
		this.bd = conexaoBanco;
	}

	@Override
	protected void execute(IProgressMonitor monitor) throws CoreException,
			InvocationTargetException, InterruptedException {
		IWorkspaceRoot workspaceRoot;
		IFolder swotFolder;
		
		try {
			monitor.beginTask("", 5000);

			workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
			swotFolder = workspaceRoot.getFolder(new Path(this.project.getName().toString()).append("\\swot\\"));			
			
			SubProgressMonitor sbm = new SubProgressMonitor(monitor, 2000);
			sbm.beginTask("", 2000);
			bd.createSchema(this.project.getName().toString(), getClass().getResource("/src/absc/bd/schema.sql").openStream());
			sbm.done();						
			
			this.project.create(this.projectDescription, new SubProgressMonitor(monitor, 1000));
			
			if (monitor.isCanceled()) {
				throw new OperationCanceledException();
			}
			this.project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 1000));
			
			if (monitor.isCanceled()) {
				throw new OperationCanceledException();
			}
			swotFolder.create(true, true, new SubProgressMonitor(monitor, 1000));
			
			monitor.done();
		}
		catch(Exception e){		
			throw (CoreException) e;
		}
	}

}
